import ScrollBarLayout from '@/components/ScrollBarLayout';
import { OneModal } from '@/components/one-ui';
import { IOneModalRef } from '@/pages/type';
import { getColorTextLoadMap, onCloseModalCommon } from '@/utils';
import { Col, Form, Input, Row, Select, Spin, message } from 'antd';
import { Ref, useRef, useEffect, useState } from 'react';
import Cls from 'classnames';
import pageStyles from '@/common/pageLayout.less';
import '../common/styles.less';
import { completeService, resolveTaskService } from '../services';

interface WorkflowCheckModalAPI {
  detailInfoObj: Record<string, any>;
  requestController: string;
  reloadCallback: () => void;
  handHelpType?: boolean;
  pageHeight?: number;
  flowBusinessType: string;
  onClose: () => void;
  clickBtnText: string;
}

export const WorkflowCheckModal: React.FC<WorkflowCheckModalAPI> = ({
  onClose,
  reloadCallback,
  detailInfoObj,
  handHelpType = false,
  requestController,
  flowBusinessType,
  clickBtnText,
}) => {
  /**样式名*/
  const prefixCls: string = 'workflow-handtasks-';

  /**表单form对象*/
  const [handleFlowForm] = Form.useForm();

  /**弹框的ref*/
  const workflowCheckModalRef: Ref<IOneModalRef> = useRef(null);

  /**下拉列表渲染对象*/
  const [selectList, setSelectList] = useState<any[]>();

  /**办理流程回调*/
  const completeCallBack = (res: any) => {
    if (res && res?.msgFlag) {
      message.success(res?.msg);
      reloadCallback();
    } else {
      message.error(res?.msg);
    }
  };

  /**引入办理流程接口*/
  const { completeLoading, completeRun } = completeService(completeCallBack, requestController);

  /**引入办理流程接口*/
  const { resolveTaskLoading, resolveTaskRun } = resolveTaskService(completeCallBack, requestController);

  /**初始化*/
  useEffect(() => {
    if (detailInfoObj?.msequenceFlowList && detailInfoObj?.msequenceFlowList?.length > 0) {
      /**默认下标为0*/
      let num = 0;
      /**找出text匹配的下标*/
      const index = detailInfoObj?.msequenceFlowList?.findIndex((item: Record<string, any>, index: number) => {
        let { colorText } = getColorTextLoadMap(item?.flowName);
        return clickBtnText == colorText;
      });
      /**如果有值，则将index赋值给num，如果找不到，则num为默认值0*/
      if (index != -1) {
        num = index;
      }
      const { colorText } = getColorTextLoadMap(detailInfoObj?.msequenceFlowList?.[num]?.flowName);
      handleFlowForm?.setFieldsValue({
        intention: detailInfoObj?.msequenceFlowList?.[num]?.flowValue,
        comment: colorText,
      });

      /**处理提交*/
      if (
        clickBtnText == '提交' &&
        !detailInfoObj?.msequenceFlowList?.findIndex((item: Record<string, any>) => item?.flowName?.indexOf('作废'))
      ) {
        setSelectList([detailInfoObj?.msequenceFlowList?.[num]]);
      } else {
        setSelectList(detailInfoObj?.msequenceFlowList);
      }
    }
  }, [detailInfoObj]);

  /**保存*/
  const onSaveHand = () => {
    handleFlowForm?.validateFields()?.then((values: any) => {
      const intentionItem: Record<string, any> = detailInfoObj?.msequenceFlowList?.find(
        (item: any) => item?.flowValue == values?.intention,
      );
      const params: any = {
        ...values,
        ...intentionItem,
        id: detailInfoObj?.id,
        orderID: detailInfoObj?.orderID,
        taskIsSign: detailInfoObj?.taskIsSign,
        procInstID: detailInfoObj?.procInstID,
        procDefID: detailInfoObj?.procDefID,
      };

      if (handHelpType) {
        resolveTaskRun(params);
      } else {
        completeRun(params);
      }
    });
  };

  const onCancelFun = () => {
    onClose();
  };

  const saveCancelOnOk = () => {
    onSaveHand();
    onCloseModalCommon(workflowCheckModalRef);
  };
  return (
    <>
      <OneModal
        open={true}
        title={'流程办理'}
        centered={true}
        getContainer={false}
        confirmLoading={completeLoading} // loading
        ref={workflowCheckModalRef}
        onCancel={onCancelFun}
        onOk={saveCancelOnOk}
        width={document.body.clientWidth * 0.3}
      >
        {/* completeLoading || resolveTaskLoading */}
        <Spin spinning={completeLoading}>
          <Row className={'cardBodyRow'}>
            <Col span={24} className={'cardBodyCol'}>
              <ScrollBarLayout>
                <div
                  className={Cls(pageStyles['fromView-stylesPage'], prefixCls + 'taskHandleFormBox')}
                  style={{
                    padding: '5px 10px',
                  }}
                >
                  <Form form={handleFlowForm}>
                    <Row>
                      <Col span={24}>
                        <Form.Item
                          name="intention"
                          label="审批意向"
                          rules={[
                            {
                              required: true,
                              message: '请选择审批意向',
                            },
                          ]}
                          initialValue={detailInfoObj?.msequenceFlowList?.[0]?.flowValue}
                        >
                          <Select
                            placeholder="请选择审核意向"
                            onSelect={(selectKey: string, otherInfo: any) => {
                              handleFlowForm?.setFieldsValue({
                                comment: otherInfo?.children,
                              });
                            }}
                          >
                            {selectList?.map((item: any) => {
                              const { colorText } = getColorTextLoadMap(item?.flowName);
                              return (
                                <Select.Option key={item?.flowValue} value={item?.flowValue}>
                                  {colorText}
                                </Select.Option>
                              );
                            })}
                          </Select>
                        </Form.Item>
                      </Col>
                      <Col span={24}>
                        <Form.Item
                          label={'批注'}
                          name="comment"
                          rules={[
                            {
                              required: true,
                              message: '请输入批注',
                            },
                          ]}
                        >
                          <Input.TextArea
                            placeholder={`请输入批注`}
                            showCount
                            maxLength={500}
                            autoSize={{ minRows: 2, maxRows: 4 }}
                          />
                        </Form.Item>
                      </Col>
                    </Row>
                  </Form>
                </div>
              </ScrollBarLayout>
              {/* <div className={'cardBodybtn'}>
                <Button
                  type={'primary'}
                  onClick={onSaveHand}
                >
                  {handHelpType ? '帮办' : '确认'}
                </Button>
              </div> */}
            </Col>
          </Row>
        </Spin>
      </OneModal>
    </>
  );
};
